package com.qcxy.gzy.activity.v3;

import android.os.Bundle;

import com.google.gson.Gson;
import com.qcxy.gzy.activity.base.BaseSwitchActivity;
import com.qcxy.gzy.bean.ComReceiveDataBean;
import com.qcxy.gzy.bean.SerialPortCommand;
import com.qxcy.gzy.util.PreferencesUtils;
import com.qxcy.gzy.util.SerialPortUtils;

import java.util.Timer;
import java.util.TimerTask;

/*
 * 此Activity主要用于切换电机
 * */
public abstract class SwitchEMActivity extends BaseSwitchActivity {
    //status当前流程状态
    // (-2-标识刹车启动命令已发送；-1-标识停止电机命令已发送状态；
    // 0-标识旧制动器关闭命令已发送；1-标识新制动器打开命令已发送；
    // 2-标识启动电机命令已发送状态；3-标识读电机状态命令已发送；
    // 4-标识刹车停止命令已发送；5-命令发送结束
    protected int needEMType;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        builder = new StringBuilder();
        builder.append("------------------------------------------------------------------------\n");
        builderW("Test");
    }

    //切换到大电机
    protected void switchToEMBig() {
        showLoadingView();
        status = -2;
        needEMType = SerialPortUtils.ElectricMachineryBig;
        controlSC(SerialPortUtils.SCStart);
    }

    //切换到小电机
    protected void switchToEMSmall() {
        showLoadingView();
        status = -2;
        needEMType = SerialPortUtils.ElectricMachinerySmall;
        controlSC(SerialPortUtils.SCStart);
    }

    private void switchEM(@SerialPortUtils.ElectricMachineryType int emType) {
        builder.append("希望切换电机:").append(emType == SerialPortUtils.ElectricMachineryBig ? "大电机" : "小电机").append("\n");
        builderW("Test");
        if (isEMRunning) {
            //电机正在运行
            if (runEMType != emType) {
                status = -1;
                //发送电机停止运行命令
                byte[] commandEMStop = SerialPortUtils.getEMCommand(runEMType, SerialPortUtils.EMActionStop);
                currentCommand = new SerialPortCommand(commandEMStop, SerialPortCommand.COM_TYPE_EM_STOP);
                sendCommand(currentCommand);
            }
        } else {
            runEMType = emType;
            status = 1;
            //电机未运行，发送制动器打开命令
            byte[] commandBrake = SerialPortUtils.getBradeCommandFromEM(runEMType, SerialPortUtils.BrakeActionOpen);
            currentCommand = new SerialPortCommand(commandBrake, SerialPortCommand.COM_TYPE_BRAKE_OPEN);
            sendCommand(currentCommand);
        }
    }

    private void controlSC(@SerialPortUtils.SCAction int action) {
        builder.append("\n****************************刹车:").append(action == SerialPortUtils.SCStart ? "启动" : "停止").append("\n");
        builderW("Test");
        byte[] command = SerialPortUtils.getSCCommand(action);
        currentCommand = new SerialPortCommand(command, action == SerialPortUtils.SCStart ? SerialPortCommand.COM_TYPE_SC_START : SerialPortCommand.COM_TYPE_SC_STOP);
        sendCommand(currentCommand);
    }

    //发送单条命令
    protected void sendCommand(SerialPortCommand command) {
        sendCommand(command, SerialPortUtils.SerialPortDefault);
    }

    /**
     * @param command   命令
     * @param delayTime 单位为10ms
     */
    protected void sendCommand(SerialPortCommand command, int delayTime) {
        if (resendThread != null) {
            resendThread.stopSend();
            resendThread = null;
        }
        resendThread = new autoResendThread(command, delayTime);
        new Thread(resendThread).start();
    }


    @Override
    protected void onDataReceived(final ComReceiveDataBean ComRecData) {
        builder.append("收到返回值1：").append(new Gson().toJson(ComRecData.bRec)).append("\n");
        builder.append("当前状态isSwitch：").append(isEMSwitching).append("\n");
        builderW("Test");
        w("收到:" + json(ComRecData.bRec));
        if (!isEMSwitching) return;
        dataParse(ComRecData);
    }

    private boolean verification(final ComReceiveDataBean ComRecData) {
        switch (currentCommand.command[1]) {
            case SerialPortUtils.typeRead://读
                return ComRecData.getCRC(ComRecData.bRec).equals("0");
            case SerialPortUtils.typeWrite://写
                return ComRecData.bRec.length >= 5;//写操作只要返回数据长度>=5即为成功
            default:
                return true;
        }
    }

    protected void dataParse(final ComReceiveDataBean ComRecData) {
        if (verification(ComRecData)) {
            isCommandRun = false;
            if (resendThread != null) {
                resendThread.stopSend();
                resendThread = null;
            }
            switch (currentCommand.command[1]) {
                case SerialPortUtils.typeRead://读
                    if (ComRecData.bRec[1] == SerialPortUtils.typeRead) {
                        if (ComRecData.bRec[4] == 0x04) {
                            isEMRunning = true;
                            PreferencesUtils.put(SwitchEMActivity.this, SerialPortUtils.EM_STATUS, true);
                            builder.append("电机启动成功，发送刹车停止命令").append("\n");
                            //电机状态为启动
                            status++;
                            //结束10s计时器
                            stopTimer();
                            //刹车关闭
                            controlSC(SerialPortUtils.SCStop);
                        } else {
                            if (timeOutNum < readWaitTime) {
                                //发送读电机状态命令
                                byte[] commandEMStatus = SerialPortUtils.getReadCommand(runEMType, SerialPortUtils.ReadEM);
                                currentCommand = new SerialPortCommand(commandEMStatus, SerialPortCommand.COM_TYPE_EM_READ);
                                sendCommand(currentCommand);
                            }
                        }
                    }
                    break;
                case SerialPortUtils.typeWrite://写
                    byte address = currentCommand.command[3];
                    byte action = currentCommand.command[5];
                    if (currentCommand.command[0] != SerialPortUtils.addressControl) {//电机操作返回
                        status++;
                        if (action == SerialPortUtils.EMActionStart) {
                            builder.append("电机启动命令发送成功，请求启动的电机为：").append(runEMType == SerialPortUtils.ElectricMachineryBig ? "大电机" : "小电机").append("\n");
                            builderW("Test");
                            //开启10s计时器
                            timeOutNum = 0;
                            startTimer();
                            //发送读电机状态命令
                            byte[] commandEMStatus = SerialPortUtils.getReadCommand(runEMType, SerialPortUtils.ReadEM);
                            currentCommand = new SerialPortCommand(commandEMStatus, SerialPortCommand.COM_TYPE_EM_READ);
                            sendCommand(currentCommand);
                        } else {
                            //停止电机成功,发送制动器关闭命令
                            builder.append("停止电机成功，当前停止的电机为：").append(runEMType == SerialPortUtils.ElectricMachineryBig ? "大电机" : "小电机").append("\n");
                            builderW("Test");
                            isEMRunning = false;
                            PreferencesUtils.put(SwitchEMActivity.this, SerialPortUtils.EM_STATUS, false);
                            //电机未运行，发送旧制动器关闭命令
                            byte[] commandBrake = SerialPortUtils.getBradeCommandFromEM(runEMType, SerialPortUtils.BrakeActionClose);
                            currentCommand = new SerialPortCommand(commandBrake, runEMType + "---" + SerialPortCommand.COM_TYPE_BRAKE_CLOSE);
                            sendCommand(currentCommand);
                        }
                    } else {//刹车与制动器操作返回
                        switch (address) {
                            case SerialPortUtils.addressSC://刹车（启动或者停止）命令返回数据
                                if (action == SerialPortUtils.SCStart) {
                                    builder.append("刹车启动成功，开始切换电机").append("\n");
                                    builderW("Test");
                                    switchEM(needEMType);
                                } else {
                                    builder.append("刹车停止成功").append("\n");
                                    builderW("Test");
                                    status++;
                                    if (isImp()) {
                                        ((SwitchEMListener) SwitchEMActivity.this).onSwitch(true, "切换成功", runEMType);
                                    }
                                }
                                break;
                            default://制动器（启动或者停止）命令返回数据
                                status++;
                                if (action == SerialPortUtils.BrakeActionOpen) {
                                    builder.append("打开制动器成功，当前打开的制动器为").append(runEMType == SerialPortUtils.ElectricMachineryBig ? "大电机制动器" : "小电机制动器").append("\n");
                                    builderW("Test");
                                    //发送电机启动运行命令
                                    byte[] commandEMStart = SerialPortUtils.getEMCommand(runEMType, SerialPortUtils.EMActionStart);
                                    currentCommand = new SerialPortCommand(commandEMStart, SerialPortCommand.COM_TYPE_EM_START);
                                    sendCommand(currentCommand);
                                } else {
                                    builder.append("关闭制动器成功，当前关闭的制动器为").append(runEMType == SerialPortUtils.ElectricMachineryBig ? "大电机制动器" : "小电机制动器").append("\n");
                                    builderW("Test");
                                    //旧电机已关闭，关联制动器已关闭，设置期望开启电机类型
                                    runEMType = runEMType == SerialPortUtils.ElectricMachineryBig ? SerialPortUtils.ElectricMachinerySmall : SerialPortUtils.ElectricMachineryBig;
                                    //发送制动器打开运行命令
                                    byte[] commandBrakeStart = SerialPortUtils.getBradeCommandFromEM(runEMType, SerialPortUtils.BrakeActionOpen);
                                    currentCommand = new SerialPortCommand(commandBrakeStart, runEMType + "---" + SerialPortCommand.COM_TYPE_BRAKE_OPEN);
                                    sendCommand(currentCommand);
                                }
                                break;
                        }
                        break;
                    }
            }
        } else {
            builder.append("校验失败\n");
            builderW("Test");
        }
    }

    //10秒切换超时计时器相关**************************************************************************
    //计时器（10s读）
    private Timer timer;
    private TimerTask task;
    private int timeOutNum = 0;

    private void initTimer() {
        timer = new Timer();
        task = new TimeOutTask();
    }

    //启动计时器
    private void startTimer() {
        /*
         * java.util.Timer.schedule(TimerTask task, long delay, long period)：
         * 这个方法是说，delay/1000秒后执行task,然后进过period/1000秒再次执行task，
         * 这个用于循环任务，执行无数次，当然，你可以用timer.cancel();取消计时器的执行。
         */
        initTimer();
        try {
            timer.schedule(task, 1000, 1000);
        } catch (IllegalStateException e) {
            e.printStackTrace();
            initTimer();
            timer.schedule(task, 1000, 1000);
        }
    }

    private void autoStopTimer() {
        if (timer != null) {
            timer.cancel();
        }
    }

    private void stopTimer() {
        if (timer != null) {
            timer.cancel();
        }
        //置零
        timeOutNum = 0;
    }

    private void destroyTimer() {
        timer = null;
        task = null;
    }

    protected class TimeOutTask extends TimerTask {

        @Override
        public void run() {
            timeOutNum++;
            if (timeOutNum >= readWaitTime) {
                autoStopTimer();
                String message = "";
                switch (status) {
                    case 1:
                    case 3:
                        message = "切换制动器失败";
                        break;
                }
                //提示用户10s切换失败
                if (isImp()) {
                    ((SwitchEMListener) SwitchEMActivity.this).onSwitch(false, message, runEMType);
                }
            }
        }
    }

    @Override
    protected void onPause() {
        super.onPause();
        //当activity不在前台是停止定时
        stopTimer();
    }

    @Override
    public void onDestroy() {
        //销毁时停止定时
        stopTimer();
        destroyTimer();
        super.onDestroy();
    }
}